const DB = require('../tools/mysql')
const path = require('path')
const fs = require('fs')

let animationType = 'rotate,rotateX,rotateY,rotateZ,rotate3d,scale,scaleX,scaleY,scaleZ,scale3d,translate,translateX,translateY,translateZ,translate3d,skew,skewX,skewY,matrix,matrix3d'

module.exports = async ctx => {
    const param = ctx.req.body ? ctx.req.body : ctx.request.body
    if (param.code == 1) {
        const images = await DB('image').where('card', param.card)
        const last = await DB('image').orderBy('id', 'desc').limit(1)
        ctx.body = {
            images: images,
            count: last[0].id
        }
    } else if (param.code == 2) {
        global.fileNum = 0
        const getInsertObj = function(id, update, updateFile) {
            const insertObj = {}
            if (!update) {
	            insertObj.id = id
	            insertObj.card = param.card
            }
            if (updateFile) {
            	insertObj.url = `${param.folder}/${updateFile}`
            }
            insertObj.background = param[`row${id}_background`]
            if (param[`row${id}_image`]) {
            	insertObj.image =  param[`row${id}_image`]
            }
            insertObj.wish_in = param.wish_in == id ? 1 : 0
            var styleText = param[`row${id}_style`]
            if (styleText) {
                const lastText = styleText.substr(0, styleText.length - 1).split(';').splice(-1)[0].split(':')[1].trim()
                const lastStyle = lastText.substr(0, lastText.length - 1).split('(')
                if (animationType.indexOf(lastStyle[0]) > -1) {
                    styleText += ` ${lastStyle[0]}: ${lastStyle[1].replace('deg', '').replace('px', '')};`
                }
            	insertObj.style = styleText
            }
            const endStyleText = param[`row${id}_endStyle`]
            const animationText = param[`row${id}_animation`]
            if (endStyleText && animationText) {
            	const temp1 = animationText.replace(/; /g, '", "').replace(/: /g, '": "')
            	const animation = JSON.parse(`{"${temp1.substr(0, temp1.length - 1)}"}`)
            	const temp2 = endStyleText.replace(/; /g, '", "').replace(/: /g, '": "')
            	const endStyleObj = JSON.parse(`{"${temp2.substr(0, temp2.length - 1)}"}`)
            	animation.animation = endStyleObj
            	insertObj.animation = JSON.stringify(animation)
            }
            return insertObj
        }
        const isok = []
        const ids = param.ids.split(',')
        const _ids = ids.filter(function(item) {
            return !param[`row${item}_image`]
        })
        for (var i = 0; i < _ids.length; i++) {
            const isexit = await DB('image').where({ id: _ids[i] })
            const fileUrl = param.files ? param.files[_ids[i] - 0] : ''
            if (isexit.length === 0) { // 添加
            	const ins = await DB('image').insert(getInsertObj(_ids[i], false, fileUrl))
                isok.push(ins.length === 1 ? 1 : 0)
            } else {
            	const u = await DB('image').where({ id: _ids[i] }).update(getInsertObj(_ids[i], true, fileUrl))
            	isok.push(u)
                const fpath = path.join(__dirname, `../public/${isexit[0].url}`)
        		if (u === 1 && fileUrl && fs.existsSync(fpath)) {
                    fs.unlinkSync(fpath)
                }
            }
        }
        const ids_ = ids.filter(function(item) {
            return param[`row${item}_image`]
        })
        for (var i = 0; i < ids_.length; i++) {
            const isexit = await DB('image').where({ id: ids_[i] })
            const fileUrl = param.files ? param.files[ids_[i] - 0] : ''
            if (isexit.length === 0) { // 添加
            	const ins = await DB('image').insert(getInsertObj(ids_[i], false, fileUrl))
                isok.push(ins.length === 1 ? 1 : 0)
            } else {
            	const u = await DB('image').where({ id: ids_[i] }).update(getInsertObj(ids_[i], true, fileUrl))
            	isok.push(u)
                const fpath = path.join(__dirname, `../public/${isexit[0].url}`)
        		if (u === 1 && fileUrl && fs.existsSync(fpath)) {
                    fs.unlinkSync(fpath)
                }
            }
        }
        const isdelete = await DB('image').where({ card: param.card })
        for (var i = 0; i < isdelete.length; i++) {
        	if (ids.indexOf(isdelete[i].id + '') === -1) {
        		const u = await DB('image').where({ id: isdelete[i].id }).del()
        		isok.push(u)
                const fpath = path.join(__dirname, `../public/${isdelete[i].url}`)
        		if (u === 1 && fs.existsSync(fpath)) {
                    fs.unlinkSync(fpath)
                }
        	}
        }
        if (isok.indexOf(0) > -1) {
        	ctx.body = { code: -1 }
        } else {
        	ctx.body = isok
        }
    }
}